package app.itgungnir.compose.wan.business.settings

import androidx.lifecycle.ViewModel
import app.itgungnir.compose.wan.WanApp
import app.itgungnir.compose.wan.utils.*
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.map

class SettingsViewModel : ViewModel() {

    val loadingState = MutableStateFlow(false)
    val errorState = MutableSharedFlow<Throwable?>()
    val dismissDialogState = MutableStateFlow(false)
    var loadingJob: Job? = null

    val showHotArticlesState = WanApp.instance.dataStore.data.map { it.showHotArticles }
    val nonPictureModeState = WanApp.instance.dataStore.data.map { it.useNonPictureMode }
    val darkModeExtendSystemState = WanApp.instance.dataStore.data.map { it.darkModeExtendSystem }
    val darkModeEnabledState = WanApp.instance.dataStore.data.map { it.darkModeEnabled }
    val colorPaletteIndexState = WanApp.instance.dataStore.data.map { it.themePaletteIndex }
    val fontSizeIndexState = WanApp.instance.dataStore.data.map { it.fontTypographyIndex }
    val cacheSizeState = MutableStateFlow("")

    init {
        getCacheSize()
    }

    fun toggleShowHotArticles(value: Boolean) = launch {
        LocalDataStore.updateLocalData {
            it.showHotArticles = value
        }
    }

    fun toggleNonPictureMode(value: Boolean) = launch {
        LocalDataStore.updateLocalData {
            it.useNonPictureMode = value
        }
    }

    fun toggleDarkModeExtendSystem(value: Boolean) = launch {
        LocalDataStore.updateLocalData {
            it.darkModeExtendSystem = value
            if (value) {
                it.darkModeEnabled = false
            }
        }
    }

    fun toggleDarkModeEnabled(value: Boolean) = launch {
        LocalDataStore.updateLocalData {
            it.darkModeEnabled = value
        }
    }

    fun toggleColorPaletteIndex(value: Int) = launch {
        LocalDataStore.updateLocalData {
            it.themePaletteIndex = value
        }
    }

    fun toggleFontSizeIndex(value: Int) = launch {
        LocalDataStore.updateLocalData {
            it.fontTypographyIndex = value
        }
    }

    fun clearCache() = launch(loadingState = loadingState, errorState = errorState) {
        dismissDialogState.value = false
        clearAllCache(WanApp.instance)
        getCacheSize()
        dismissDialogState.value = true
    }.also { loadingJob = it }

    private fun getCacheSize() = launch {
        cacheSizeState.value = getTotalCacheSize(WanApp.instance)
    }
}
